// 获取应用实例
const request=require('../../utils/request.js');//获取封装的请求函数
const globleurl = require('../../utils/serverconfig.js').url;
const appInstance = getApp();
const { globalData: { defaultCity, defaultCounty } } = appInstance;


Page({
    
    data: {

        //轮播图数据
        banner: [],
        //电影列表数据
        hotmovielist: [],
        recentmovielist:[],
        tab:1,
        //轮播图是否显示
        bannershow: true,
        //点击热映待映添加样式类，为1给热映添加，为2给待映添加
        num: 1,

        //城市数据
        location: defaultCity,
        county: defaultCounty,

        search:false,
   
    },



    // 事件处理函数

    onLoad() {

    },

    // 搜索
    search(e){

      this.setData({
        search:true
      });

    },

  // 搜索
    confirmsearch(e){
      // e.detail
      console.log(e);
      wx.navigateTo({
        url: `../search/search?value=${e.detail}`
      })
      
    },

    // 取消搜索
    canclesearch(){
      this.setData({
        search:false
      });
    },

    //网络错误
    networkRetry(){
      appInstance.initPage();
      this.requestmovielist(this,3);
    },

    //请求轮播图数据函数
    bannerrequest:async (_this)=>{
      try {
        let bannerdata=await request.myrequest('/miniapp/banner');
        if(bannerdata){
         bannerdata.data.forEach(item=>{
             item.url=globleurl+item.url;
        });
        _this.setData({
            banner:bannerdata.data
        });
        //存入缓存
        wx.setStorageSync('bannersession', {banner:_this.data.banner,time:Date.now()});
        };  
      } catch (error) {
        _this.bannerrequest(_this);
      }
  
    },

    //请求电影数据,请求playstate为3热映，2待映
    requestmovielist:async (_this,playstate)=>{
       let movielist=await request.myrequest('/miniapp/movielist',{playstate:playstate});
      //如果服务器请求错误
      let rg=/^[23]\d{2}$/;
      if(!rg.test(movielist.statusCode)){
        _this.setData({
          showNetworkerr:true,
        });
        return;
      };
       movielist.data.forEach(item=>{
          item.img_url=globleurl+item.img_url;
       });
       if(parseInt(playstate)==2){ 
         _this.setData({
          recentmovielist:movielist.data
         });
       };
       if(parseInt(playstate)==3){ 
         _this.setData({
          hotmovielist:movielist.data,
          showloding:false,
          showNetworkerr:false
       });
       wx.setStorageSync('hotmoviesession', {hotmovielist:movielist.data,time:Date.now()});
      };   
       wx.stopPullDownRefresh();  
    },


    buy(){
      wx.switchTab({
        url: '../cinema/cinema',
      })
    },


    // 热映待映点击事件
    hotplaytap: function() {

        var _this=this;
        //请求电影列表
        _this.requestmovielist(_this,3);
        //给热映添加样式类，同时让banner显示，并且切换tab为1
        this.setData({
            num: 1,
            bannershow: true,
            tab:1
        })
    },
    recentplaytap: function() {

        var _this=this;
        //请求电影列表
        _this.requestmovielist(_this,2);
        //给待映添加样式类，同时让banner隐藏,并且切换tab为2
        this.setData({
            num: 2,
            bannershow: false,
            tab:2
        })
    },

    onShow:function(){
     
        const { globalData: { defaultCity, defaultCounty } } = appInstance
        this.setData({
          location: defaultCity,
          county: defaultCounty
        });

        var _this=this;
        //请求轮播图数据
        let bannersession=wx.getStorageSync('bannersession');
        if(!bannersession){
          //如果轮播图缓存不存在
          _this.bannerrequest(_this);
        }else{
          //存在
          let time=180;
           if(Date.now()-bannersession.time>1000*time){
             //过期
             _this.bannerrequest(_this);
           }else{
            //  没有过期
            this.setData({
              banner:bannersession.banner
            });
           }
        }

        //请求热映电影数据
        let hotmoviesession=wx.getStorageSync('hotmoviesession');
        if(!hotmoviesession){
          _this.requestmovielist(_this,3);
        }else{
          //缓存时间180秒
          let time=180;
          //计算公式：当前时间戳-缓存时时间戳=经过的时间
          if(Date.now()-hotmoviesession.time>1000*time){
            //缓存过期
            _this.requestmovielist(_this,3);
          }else{
           //  缓存没有过期
           this.setData({
            hotmovielist:hotmoviesession.hotmovielist,
 
           });
          }
        }
           
        //请求热映电影数据
        
        _this.cityInit();
      
    },

    //选择定位
    selectlocation:function(e){
        wx.redirectTo({
          url: '../selectlocation/pages/switchcity/switchcity?index=0',
        })
    },
    cityInit:function() {
        if (appInstance.globalData.userLocation) {
          this.setData({
            location: appInstance.globalData.defaultCity ? appInstance.globalData.defaultCity : '定位失败'
          })
        } else {
            appInstance.userLocationReadyCallback = () => {
 
            this.setData({
                location: appInstance.globalData.defaultCity ? appInstance.globalData.defaultCity : '定位失败'
            })
          }
        }
      },
    
    //上拉刷新
    onPullDownRefresh(){
      this.setData({
        banner:[],
        hotmovielist:[],
        recentmovielist:[]
      });
      wx.removeStorageSync('bannersession')
      this.bannerrequest(this);
      this.requestmovielist(this,3);
      this.requestmovielist(this,2);
      appInstance.initPage()
      appInstance.userLocationReadyCallback = () => {
        this.cityInit()
      }
    
    }
    
})